package com.example.petshop.service.impl;

import com.example.petshop.entity.Cart;
import com.example.petshop.entity.Goods;
import com.example.petshop.entity.User;
import com.example.petshop.mapper.CartMapper;
import com.example.petshop.mapper.GoodsMapper;
import com.example.petshop.service.CartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class CartServiceImpl implements CartService {

    @Autowired
    private CartMapper cartMapper;

    @Autowired
    private GoodsMapper goodsMapper;

    @Override
    public boolean addToCart(Integer goodsId,String goodsName,String description,String images,String price,Integer shopId,Long  userId,Integer quantity) {
        // 检查商品是否存在
        Goods goods = goodsMapper.selectById(goodsId);
        if (goods == null) {
            return false; // 商品不存在，返回失败
        }

        // 检查购物车中是否已存在该商品
        Cart existingCart = cartMapper.getCartByGoodsIdAndUserId(goodsId, userId);
        if (existingCart != null) {
            // 如果存在，则更新数量
            existingCart.setQuantity(existingCart.getQuantity() + 1);
            return cartMapper.updateCart(existingCart) > 0;
        } else {
            // 如果不存在，则创建新的购物车条目
            Cart cart = new Cart();
            cart.setGoodsId(goodsId);
            cart.setImages(images);
            cart.setGoodsName(goodsName);
            cart.setDescription(description);
            cart.setShopId(shopId);
            cart.setPrice(price);
            cart.setUserId(userId);
            cart.setQuantity(quantity); // 新添加的商品数量为quantity

            // 保存到购物车
            return cartMapper.insert(cart) > 0;
        }
    }

    @Override
    public List<Cart> getCartsByUserId(Long userId) {
        return cartMapper.getCartsByUserId(userId);
    }

    @Override
    public boolean updateCartQuantity(Integer cartid, Integer quantity) {
        // 调用 CartMapper 的方法来更新购物车数量
        int updatedRows = cartMapper.updateQuantityById(cartid, quantity);

        // 如果更新的行数大于0，则说明更新成功
        return updatedRows > 0;
    }

    @Override
    public List<Cart> getAllCarts() {
        return cartMapper.getAllCarts();
    }

    @Override
    public boolean deleteCartById(Integer cartid) {
        return cartMapper.deleteById(cartid) > 0;
    }

    @Override
    public boolean deleteCartsByIds(List<Integer> cartids) {
        return cartMapper.deleteByIds(cartids) > 0;
    }
}
